package com.apes.hr.cultivate.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.DateUtil;
import com.apes.hr.cultivate.repository.CourseRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apestech.framework.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * 培训计划安排
 * @author Linwz
 * @create 2019-06-18 10:11
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = CultivatePlanArrange.CONST_TABLE_NAME)
public class CultivatePlanArrange extends Model {
    public static final String CONST_TABLE_NAME = "hr_cultivate_plan_arrange";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "培训计划安排", prefix = "A")
    @Comment("培训计划安排编码")
    private String id;   //培训计划安排编码

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cultivate_plan_id", referencedColumnName = "ID")
    @Comment("培训计划")
    private CultivatePlan cultivatePlan; //培训计划

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "serve_state_date")
    @Comment("约定培训服务器起")
    private Date serveStateDate;  //约定培训服务器起

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "serve_end_date")
    @Comment("约定培训服务器止")
    private Date serveEndDate;  //约定培训服务器止


    @Column(name = "state", length = 16)
    @Comment("状态")
    private String state;   //状态

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审批人")
    private PartyRole approveUid; //审批人

    @Column(name = "approve_date")
    @Comment("审批日期")
    private Date approveDate; //审批日期

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_id", referencedColumnName = "id")
    private PartyRole deleteId; //删除人

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "delete_date")
    private Date deleteDate;    // 删除日期

    @OneToMany(mappedBy="cultivatePlanArrange",cascade=CascadeType.ALL)
    private Set<CultivatePlanArrangeItem> cultivatePlanArrangeItems = new HashSet<>();//参训人员名单
    public Set<CultivatePlanArrangeItem> getCultivatePlanArrangeItems() {
        if (cultivatePlanArrangeItems == null) return null;
        for (CultivatePlanArrangeItem item: cultivatePlanArrangeItems) {
            item.setCultivatePlanArrange(this);
        }
        return cultivatePlanArrangeItems;
    }

    @Column(name = "course_list", length = 4000)
    @Comment("课程列表")
    private String courseList;  //课程列表

    public void setCourseLists(String courseList) {
    }

    @Transient
    private Set<Course> courseSet;

    public Set<Course> getcourseSet() {
        if (isWrite() || isLoad()) {
            courseSet = getCourse(this.courseList);
        }
        return courseSet;
    }
    public void setcourseSet( Set<Course> courseSet) {
        this.courseSet = courseSet;
        if (!isWrite()) {
            this.courseList = toConvertCourse(this.courseSet);
        }
    }

    @Transient
    private Set<Course> getCourse(String source) {
        if (StringUtil.isEmpty(source)) return null;
        Set<Course> persons = new HashSet<>();
        String[] rows = source.split(";");
        for (String person : rows) {
            if (person.contains("|")) {
                persons.add(SpringManager.getBean(CourseRepository.class).findOne(StringUtils.split(person, "|")[0]));
            }
        }
        return persons;
    }

    private String toConvertCourse(Set<Course> persons) {
        StringBuffer sb = new StringBuffer();
        for (Course course : persons) {
            if (sb.length() > 0) {
                sb.append(";");
            }
            sb.append(course.getId());
            sb.append("|");
            sb.append(course.getName());  // 格式 id|description;
        }
        return sb.toString();
    }


}
